import fs from 'fs';
import lodash from 'lodash';
import puppeteer from "../../../lib/puppeteer/puppeteer.js";
import {
    createAGroupFolder,
    deletePlayerData,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    PLUGIN_PATH,
    storagePlayerData,
    getConfig,
    formatCurrency,
    checkPermission,
    checkAndPerformWeeklyReset,
    getLastWeekRankingHistory,
    formatRankingMessage
} from '../function/function.js';

// 读取JSON文件
const copywriting = JSON.parse(fs.readFileSync('plugins/Slave-Market/resources/data/workCopywriting.json', 'utf-8'));

export class Sm extends plugin {
    constructor() {
        super({
            name: '[Sm]打工',
            dsc: '打工',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/](一键)?(打工|工作)$/, fnc: 'work' }
            ]
        })
    }

    async work(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 检查并执行每周重置
        const resetResult = await checkAndPerformWeeklyReset();
        if (resetResult && resetResult.success) {
            await e.reply([`🔄 每周重置已自动执行！重置了${resetResult.resetCount}个玩家数据`]);
            
            // 显示上周排行榜
            await this.showLastWeekRankingsAfterReset(e);
        }

        // 读取配置
        const config = getConfig();

        // 检查群组和玩家是否存在，不存在则创建
        if (!isGroupExist(ID[1])) createAGroupFolder(ID[1]);
        if (!isPlayerExist(ID[1], ID[0])) {
            await storagePlayerData(ID[1], ID[0], {
                currency: 0,
                slave: [],
                value: 100,
                lastWorkingTime: 0,
                master: '',
                nickname: e.sender.card || e.sender.nickname
            });
        } else {
            // 更新昵称
            const userData = await getPlayerData(ID[1], ID[0]);
            await storagePlayerData(ID[1], ID[0], userData, e.sender.card || e.sender.nickname);
        }

        try {
            const userData = await getPlayerData(ID[1], ID[0]);
            const { currency, slave, value, lastWorkingTime } = userData;

            const currentSecond = Math.floor(Date.now() / 1000);
            const remainingTime = {
                h: Math.floor(Math.abs(currentSecond - lastWorkingTime) / 3600),
                m: Math.floor(Math.abs(currentSecond - lastWorkingTime) % 3600 / 60),
                s: Math.abs(currentSecond - lastWorkingTime) % 60
            };

            // 检查冷却时间
            if (!checkPermission(e) && currentSecond - lastWorkingTime < 0) {
                const timeMsg = `每${config.work.cooldown / 3600}小时一次，剩余CD：`;
                const timeReply = remainingTime['h'] > 0 ? `${remainingTime['h']}时${remainingTime['m']}分${remainingTime['s']}秒` :
                    remainingTime['m'] > 0 ? `${remainingTime['m']}分${remainingTime['s']}秒` : `${remainingTime['s']}秒`;
                return e.reply([segment.at(ID[0]), `${timeMsg}${timeReply}`]);
            }

            let wages = 0, msg = '';
            if (slave.length === 0) {
                // 如果没奴隶
                if (e.isMaster) {
                    // 如果是Bot主人
                    wages = lodash.random(100, 2000) + lodash.random(parseInt(value / 10), parseInt(value / 5));
                    msg = '您是尊贵的奴隶主\r' + '【您】' + lodash.sample(copywriting.slaveowner) + `${wages}金币` + `\r当前共有${currency + wages}金币`;
                    userData['currency'] = formatCurrency(userData['currency'] + wages);
                    userData['lastWorkingTime'] = currentSecond + config.work.slaveownerCooldown;
                    await storagePlayerData(ID[1], ID[0], userData);
                } else {
                    // 如果是群友
                    wages = lodash.random(10, 100) + lodash.random(parseInt(value / 20), parseInt(value / 10));
                    msg = '你没有群友只能自己去打工\r' + '【你】' + lodash.sample(copywriting.success) + `${wages}金币` + `\r当前共有${currency + wages}金币`;
                    userData['currency'] = formatCurrency(userData['currency'] + wages);
                    userData['lastWorkingTime'] = currentSecond + config.work.cooldown;
                    await storagePlayerData(ID[1], ID[0], userData);
                }
            } else {
                // 有奴隶时的打工逻辑
                let workData = [];
                // 遍历奴隶
                for (const QQ of slave) {
                    if (!isPlayerExist(ID[1], QQ)) {
                        logger.warn(`奴隶存档不存在: 群${ID[1]} 用户${QQ}`);
                        deletePlayerData(ID[1], QQ);
                        userData['slave'] = userData['slave'].filter(a => a !== QQ);
                        await storagePlayerData(ID[1], ID[0], userData);
                        continue;
                    }
                    // 确保slaveData和values正确初始化
                    let slaveData = await getPlayerData(ID[1], QQ);
                    let values = slaveData['value'];

                    // 随机打工收入
                    let wages_ = lodash.random(5, 20) + lodash.random(parseInt(values / 20), parseInt(values / 10));
                    
                    // 添加重试机制获取群成员信息
                    let retryCount = 0;
                    let memberInfo = null;
                    const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);
                    
                    while (retryCount < 3) {
                        try {
                            memberInfo = memberInfoList[QQ];
                            if (memberInfo) break;
                            
                            // 如果获取不到，重新获取群成员列表
                            const newMemberList = await Bot.pickGroup(ID[1]).getMemberMap();
                            Object.assign(memberInfoList, Object.fromEntries([...newMemberList]));
                            retryCount++;
                            
                            if (retryCount < 3) {
                                await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒后重试
                            }
                        } catch (err) {
                            logger.error(`获取群成员信息失败: ${err}`);
                            retryCount++;
                            if (retryCount < 3) {
                                await new Promise(resolve => setTimeout(resolve, 1000));
                            }
                        }
                    }

                    // 只有在多次重试后仍然获取不到成员信息时才删除
                    if (!memberInfo && retryCount >= 3) {
                        logger.warn(`无法获取奴隶信息，可能已退群: 群${ID[1]} 用户${QQ}`);
                        deletePlayerData(ID[1], QQ);
                        userData['slave'] = userData['slave'].filter(a => a !== QQ);
                        await storagePlayerData(ID[1], ID[0], userData);
                        continue;
                    }

                    // 检查奴隶是否在线
                    if (lodash.random(1, 10) !== 1) {
                        const workMsg = lodash.sample(copywriting.success);
                        // 奴隶在线时的打工收入
                        workData.push({ 
                            name: memberInfo['nickname'], 
                            work: workMsg, 
                            income: `${wages_}金币` 
                        });
                    } else {
                        wages_ = 0;
                        const workMsg = lodash.sample(copywriting.failure)
                            .replace(/\[A\]/g, `【${memberInfo['nickname']}】`)
                            .replace(/\[C\]/g, slaveData['value'])
                            .replace(/\[D\]/g, slaveData['value'] - 20);
                        workData.push({ 
                            name: memberInfo['nickname'], 
                            work: workMsg, 
                            income: '' 
                        });
                        slaveData['value'] = parseFloat(Math.max(0, slaveData['value'] - 20).toFixed(1));
                        await storagePlayerData(ID[1], QQ, slaveData);
                    }
                    wages += wages_;
                }

                userData['currency'] = formatCurrency(userData['currency'] + wages);
                userData['lastWorkingTime'] = currentSecond + config.work.cooldown;
                await storagePlayerData(ID[1], ID[0], userData);

                const totalIncome = wages;
                const currentBalance = currency + wages;

                const image = await puppeteer.screenshot('打工详情', {
                    tplFile: 'plugins/Slave-Market/resources/html/work/index.html',
                    filePath: `${PLUGIN_PATH}/resources/`,
                    workData, wages: totalIncome, assets: currentBalance
                });
                await e.reply([image]);

                // 随机触发费用事件
                if (lodash.random(1, 10) <= 2) { // 20%的概率触发
                    const expenseEvent = lodash.sample(copywriting.expenses);
                    const expenseAmount = parseInt(expenseEvent.match(/\d+/)[0]);
                    userData['currency'] = formatCurrency(Math.max(0, userData['currency'] - expenseAmount));
                    msg += `\n${expenseEvent}`;
                }
            }

            return e.reply(msg);

        } catch (error) {
            logger.error('处理打工请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }

    // 显示上周排行榜的简化版本（自动重置后）
    async showLastWeekRankingsAfterReset(e) {
        try {
            const groupId = e.group_id;
            const lastWeekData = getLastWeekRankingHistory(groupId);
            
            if (!lastWeekData) {
                return;
            }

            // 发送简化的排行榜信息
            setTimeout(async () => {
                await e.reply([
                    `🏆 ${lastWeekData.year}年第${lastWeekData.week}周排行榜回顾\n`,
                    `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`
                ]);
                
                // 只显示金币和身价排行榜前5名
                if (lastWeekData.currencyRanking && lastWeekData.currencyRanking.length > 0) {
                    const topCurrency = lastWeekData.currencyRanking.slice(0, 5);
                    const currencyMsg = formatRankingMessage(topCurrency, '上周金币排行榜TOP5');
                    await e.reply(currencyMsg);
                }
                
                setTimeout(async () => {
                    if (lastWeekData.valueRanking && lastWeekData.valueRanking.length > 0) {
                        const topValue = lastWeekData.valueRanking.slice(0, 5);
                        const valueMsg = formatRankingMessage(topValue, '上周身价排行榜TOP5');
                        await e.reply(valueMsg);
                    }
                    
                    setTimeout(async () => {
                        await e.reply([
                            '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n',
                            '🎉 新的一周开始了！使用 #上周排行榜 查看完整排行'
                        ]);
                    }, 1000);
                }, 1000);
            }, 1000);
            
        } catch (error) {
            logger.error('[简化排行榜显示]出错:', error);
        }
    }
}
